# 读取文件
def read_file(path):
    with open(path, mode="r", encoding="UTF-8") as file:
        return [line.rstrip() for line in file.readlines()]


# 处理分数表
def com_socre(sum_list):
    # 用于保存结果列表
    id_sco_list = []
    for id_sco in sum_list:
        # 分割学号和分数
        split = id_sco.split("\t")
        id = split[0]
        sco = int(split[1])
        # 将学号和分数保存到列表中
        id_sco_list.append((id, sco))

    return id_sco_list


# 取出学号和姓名
def com_students(students_list):
    id_name_list = []
    for student in students_list:
        split = student.split(",")
        id = split[0]
        name = split[1]
        id_name_list.append((id, name))

    return id_name_list


# 关联学生表和分数表
def join_score_name(id_score_list, id_name_dict):
    # 保存结果列表
    id_name_sco_list = []

    # 循环分数表，使用学号到学生表的字典中获取姓名
    for id, sco in id_score_list:
        # 通过学号获取姓名
        name = id_name_dict[id]

        id_name_sco_list.append((id, name, sco))

    # 返回结果
    return id_name_sco_list


# 保存结果
def to_file(id_name_sco, path):
    with open(path, mode="w", encoding="UTF-8") as file:
        for id, name, sco in id_name_sco:
            file.write("{}\t{}\t{}\n".format(id, name, sco))


if __name__ == '__main__':
    # 1、读取总分表
    sum_list = read_file("../../data/sum_score.txt")

    # 取出学号和分数
    id_score_list = com_socre(sum_list)

    # 2、读取学生表
    students_list = read_file("../../data/students.txt")

    # 取出学号和姓名
    id_name_list = com_students(students_list)

    # 3、将学生表转换成字典
    id_name_dict = dict(id_name_list)

    # 4、关联总分表和学生表
    id_name_sco = join_score_name(id_score_list, id_name_dict)

    # 5、保存结果
    to_file(id_name_sco, "../../data/id_name_score.txt")
